<?php
namespace Hawk\Model;
use Think\Model;
use Think\Model\RelationModel;
class RoleModel extends RelationModel 
{
	protected $insertFields = array('role_name','pid');
	protected $updateFields = array('id','role_name','pid');
	protected $_validate = array(
		array('role_name', 'require', '角色名称不能为空！', 1, 'regex', 3),
		array('role_name', '1,30', '角色名称的值最长不能超过 30 个字符！', 1, 'length', 3),
	);
	public function search($pageSize = 3)
	{
		/**************************************** 搜索 ****************************************/
		$where = array();
		/************************************* 翻页 ****************************************/
		$count = $this->alias('a')->where($where)->count();
		$page = new \Think\Page($count,$pageSize);
		//print_r($page);
		// 配置翻页的样式
		$page->setConfig('prev', '上一页');
		$page->setConfig('next', '下一页');
		$data['page'] = $page->show();
		/************************************** 取数据 ******************************************/
		 
		$data['data']=$this->alias('a')->field('a.*,c.pri_name')->join('LEFT JOIN hawk_role_privilege b on a.id = b.role_id LEFT JOIN hawk_privilege c on b.pri_id=c.id')->where($where)->select();
		//$data['roleArr'] = $this->limit($page->firstRow.','.$page->listRows)->select();
		//print_r($data['roleArr']);die;

		return $data;
	}
	// 添加前
	protected function _before_insert(&$data, $option)
	{
	}
	protected function _after_insert($data,$option){
		//添加后向role_privilege插数据

		$pri_id = I('post.pri_id');
            if($pri_id){
                $rpmodel = M('RolePrivilege');
                foreach($pri_id as $v){
                    $rpmodel->add(array(
                        'role_id'=>$data['id'],
                        'pri_id'=>$v,
                    ));
                }
            }
	}
	// 修改前
	protected function _before_update($data, $option)
	{
		$rpmdoel = M('RolePrivilege');
        $rpmdoel->where(array('role_id'=>array('eq',$option['where']['id'])))->delete();
		$pri_id = I('pri_id');
            if($pri_id){
                $rpmodel = M('RolePrivilege');
                foreach($pri_id as $v){
                    $rpmodel->add(array(
                        'role_id'=>$option['where']['id'],
                        'pri_id'=>$v,
                    ));
                }
            }
	}
	// 删除前
	protected function _before_delete($option)
	{
		
		//判断当前角色是否分配
		$armodel = M('AdminRole');
		$num = $armodel->where('role_id=\''.$option['where']['id'].'\'')->count();
		if ($num) {
			$this->error='该角色已经被分配！';
			return false;
		}

		//没有被分配，进行权限删除
		$rpmdoel = M('RolePrivilege');
        $rpmdoel->where(array('role_id'=>array('eq',$option['where']['id'])))->delete();
		if(is_array($option['where']['id']))
		{
			$this->error = '不支持批量删除';
			return FALSE;
		}
	}
	/************************************ 其他方法 ********************************************/
}